<!--  -->
<template>
  <div>动态表单
    <button @click="add">添加</button>
    <button @click="avg">统计</button>

    总数{{counts }}

    平均年龄{{ avgAge }}

    {{ editIndex }}

    <el-table :data="list" height="250" style="width: 100%">
    <el-table-column prop="name" label="姓名" width="180">
        <template #default="scope">

            <el-input v-if="scope.$index===editIndex " v-model="scope.row.name"></el-input>
               <span  v-else>{{scope.row.name}}</span>
            
             
        </template>
    </el-table-column>
    <el-table-column prop="name" label="性别" width="180">
        <template #default="scope">

            <el-input v-if="scope.$index===editIndex" v-model="scope.row.gender"></el-input>
               <span  v-else>{{scope.row.gender}}</span>
            
             
        </template>
    </el-table-column>
    <el-table-column prop="age" label="年龄" />
    <el-table-column  label="删除" >
        <template #default="scope">
            <el-button @click="edit(scope.$index)">编辑</el-button>
          <el-button>删除</el-button>
        </template>
    </el-table-column>
  </el-table>
    <table>
      <tr>
       <th>姓名</th><th>性别</th><th>年龄</th><th>删除</th>
      </tr>

      <tr v-for="(item,index) in list" :key="item.id">
       <td><input ></td><td><input ></td>
       <td><input v-model="item.age" @input="handleInput" >
       </td>
       <td><button @click="del(index)">删除</button></td>
      </tr>

    </table>
  </div>
</template>

<script lang='ts' setup>
import { reactive,toRefs,ref,computed} from 'vue'

const editIndex=ref(-1);
const editFld=ref("");

const edit2=(index:number,fld:string)=>{
    editFld.value=fld;

editIndex.value=index;
}


const edit=(index:number)=>{

    console.log(index);
    
    editIndex.value=index;
}


 
 
const list=ref([{id:Symbol("id"),name:"张三",gender:"",age:""}]);
const add=()=>{
 
    list.value.push({id:Symbol("id"),name:"",gender:"",age:""});
}

const del=(index:number)=>{

    console.log(index);
    
 if(list.value.length<2) return;
    list.value.splice(index,1);

}

const handleInput=(e:any)=>{

    
    if(!(/^[1-9]\d*$/.test(e.target.value))){
        e.target.value="";
    }

 
    

}
const counts=ref<any>(0);
const avgAge=ref<any>(0);

const avg=()=>{

     counts.value=list.value.length;

    let sum= list.value.reduce((a,b:any)=>a+Number(b.age),0);


    avgAge.value=  sum/counts.value;

}

 

</script>
<style scoped>
</style>